#ifndef PACKETCAPTURER_H
#define PACKETCAPTURER_H

#include <QObject>
#include <QList>
#include <QString>
#include <QThread>
#include <QMutex>
#include <pcap.h>
#include "common.h"

// 网卡适配器信息结构体
struct AdapterInfo {
    QString name;
    QString description;
};

class PacketCapturer : public QObject
{
    Q_OBJECT
public:
    explicit PacketCapturer(QObject *parent = nullptr);
    ~PacketCapturer();

    // 获取可用网卡列表
    QList<AdapterInfo> getAvailableAdapters();

    // 开始捕获数据包
    bool startCapture(const QString &adapterName);

    // 停止捕获数据包
    void stopCapture();

    // 检查是否正在捕获
    bool isCapturing() const;

signals:
    // 捕获到数据包时发出的信号
    void packetCaptured(const PacketInfo &packetInfo);

    // 捕获开始时发出的信号
    void captureStarted();

    // 捕获停止时发出的信号
    void captureStopped();

    // 捕获出错时发出的信号
    void captureError(const QString &errorMsg);

private slots:
    // 线程运行函数，实际执行捕获逻辑
    void runCapture();

private:
    // 解析数据包
    static PacketInfo parsePacket(const u_char *packetData, int length);

    // 解析IPv4数据包
    static void parseIPv4Packet(const u_char *packetData, int length, PacketInfo &packet);

    // 解析IPv6数据包
    static void parseIPv6Packet(const u_char *packetData, int length, PacketInfo &packet);

    // 解析ARP数据包
    static void parseARPPacket(const u_char *packetData, int length, PacketInfo &packet);

    // 解析TCP数据包
    static void parseTCPPacket(const u_char *transportHeaderData, int remainingLength, PacketInfo &packet);

    // 解析UDP数据包
    static void parseUDPPacket(const u_char *transportHeaderData, int remainingLength, PacketInfo &packet);

    // 解析ICMP数据包
    static void parseICMPPacket(const u_char *transportHeaderData, int remainingLength, PacketInfo &packet);

    // 解析ICMPv6数据包
    static void parseICMPv6Packet(const u_char *transportHeaderData, int remainingLength, PacketInfo &packet);

    // 解析IGMP数据包
    static void parseIGMPPacket(const u_char *transportHeaderData, int remainingLength, PacketInfo &packet);

    // 捕获回调函数
    static void packetHandler(u_char *userData, const struct pcap_pkthdr *pkthdr, const u_char *packetData);

    // 成员变量
    QThread *m_captureThread;
    pcap_t *m_pcapHandle;
    bool m_isCapturing;
    QString m_currentAdapter;
    QMutex m_mutex;
};

#endif // PACKETCAPTURER_H